package com.cloud.applogic;

import com.cloud.models.User;
import com.cloud.pages.MyProfilePage;
import org.openqa.selenium.Cookie;

import java.util.Set;

public class UserHelper extends DriverBasedHelper {

    //Constructor
    public UserHelper(ApplicationManager app) {
        super(app.getWebDriver());
    }

    //Methods
    public void loginAs(User user) {
        pages.loginPage.ensurePageLoaded()
                .setEmailField(user.getEmail())
                .setPasswordField(user.getPassword())
                .clickSubmitButton();
    }

    public void logout() {
        String title = pages.getWebDriver().getTitle();
        if (!title.equals("Sign in - Swivl") &&
                !title.equals("Forgot password - Swivl") &&
                !title.equals("Sign up - Swivl") &&
                !title.equals("Terms | Swivl") &&
                !title.equals("Privacy Policy | Swivl")) {
            if (pages.internalPage.isLoaded()) {
                pages.internalPage.logout();
            }
        }
    }

    public boolean isLoggedIn() {
        return pages.internalPage.isLoaded();
    }

    public boolean isNotLoggedIn() {
        return pages.loginPage.isLoaded();
    }

    public boolean isLoggedInAs(User user) {
        return isLoggedIn() && getLoggedInUser().getEmail().equals(user.getEmail());
    }

    public void checkKeepMeLoggedIn() {
        pages.loginPage.ensurePageLoaded().selectKeepMeLoggedIn();
    }

    private User getLoggedInUser() {
        MyProfilePage myProfilePage = pages.internalPage.ensurePageLoaded().openMyProfile();
        return new User(myProfilePage.getEmail(), "");
    }

    public boolean isRememberMeCookiePresent() {
        Set<Cookie> allCookies = driver.manage().getCookies();
        boolean result = false;
        for (Cookie loadedCookie : allCookies) {
            if (loadedCookie.getName().equals("REMEMBERME")) {
                result = true;
                break;
            }
        }
        return result;
    }

}
